//
//  NetworkTools.swift
//  02-AFN网络工具
//
//  Created by 陈伟 on 15/10/16.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import UIKit
import AFNetworking

enum CWRequestType: String{
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
//    private let appKey: String = "3863118655"
//    private let appSecret: String = "b94c088ad2cdae8c3b9641852359d28c"
    
    private let appKey: String = "3445132615"
    private let appSecret: String = "bebc5017855f1a5e4aa8e057371a7103"
//    private let appKey: String = "1632215437"
//    private let appSecret: String = "f950ac0e234a9d857e2bbd1a6c541345"
    private let redirect: String = "http://www.baidu.com"
    
    typealias CWFinishedCallBack = (result: AnyObject?, error: NSError?)->()
    //单例网络工具
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools(baseURL: nil)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
//    private var tokenDict: [String: AnyObject]? {
//        if let token = UserAccountViewModel.sharedUserAccount.cwAccessToken{
//            return ["access_token": token]
//        }
//        return nil
//    }
}

//OAuth相关
extension NetworkTools {
    //拼接授权页面地址
    var oauthURL: NSURL {
        
        let urlString: String = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect)"
        
        return NSURL(string: urlString)!
    }
    
    //拿到网络授权码之后拼接发送请求
    func loadAccessToken(code: String, finished: CWFinishedCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"

        let parameter = [
            "code" : code,
            "client_id" : appKey,
            "client_secret" : appSecret,
            "grant_type": "authorization_code",
            "redirect_uri": "http://www.baidu.com"]

        request(.POST, URLString: urlString, parameters: parameter, finished:finished)
    }
    
    //通过Token值来获取用户信息
    func loadUserInfo(uid: String, accessToken: String, finished: CWFinishedCallBack) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
//        guard var parameters = tokenDict else {
//            finished(result: nil, error: NSError(domain: "chnvi", code: -1001, userInfo: ["message": "token为空"]))
//            return
//        }
        let parameters = ["uid": uid,
            "access_token": accessToken
        ]
        request(.GET, URLString: urlString, parameters: parameters, finished: finished)
    }
    
    //微博数据相关
    func loadStatus(since_id since_id: Int, max_id: Int, finished: CWFinishedCallBack) {
        
        //上拉下拉刷新
        // since_id	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
        //max_id	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
//        guard var parameters = tokenDict else {
//            finished(result: nil, error: NSError(domain: "chnvi", code: -1001, userInfo: ["message": "token为空"]))
//            return
//        }
        let accessToken = UserAccountViewModel.sharedUserAccount.userAccount?.access_token
        
        var param = ["access_token": accessToken ?? ""]
        if since_id > 0 {
            param["since_id"] = "\(since_id)"
        }else if  max_id > 0 {
            param["max_id"] = "\(max_id - 1)"
        }
//        print("param" + "\(param)")
        request(.GET, URLString: urlString, parameters: param) { (result, error) -> () in
            
            finished(result: result, error: error)
            
        }
    }
    
    func composeStatus(status: String, finished:CWFinishedCallBack) {
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
//        guard var parameters = tokenDict else {
//            finished(result: nil, error: NSError(domain: "chnvi", code: -1001, userInfo: ["message": "token为空"]))
//            return
//        }
        
        var parameters = [String: AnyObject]()
        parameters["accessToken"] = UserAccountViewModel.sharedUserAccount.userAccount?.access_token
        parameters["status"] = status
        
        request(.POST, URLString: urlString, parameters: parameters) { (result, error) -> () in
            finished(result: result, error: error)
        }
    }
}

//封装AFN工具
extension NetworkTools{
    
    private func request(requestType: CWRequestType, URLString: String, parameters: [String: AnyObject ]?, finished:(result: AnyObject?, error: NSError?)->()) {
        
        
        let success = {  (task:NSURLSessionDataTask,  result: AnyObject) -> Void in
            
            finished(result: result, error:nil)
        }
        
        let failure = { (task: NSURLSessionDataTask, error: NSError) -> Void in
            
            finished(result: nil, error: error)
            print("tool管理里error:" + "\(error)")
        }
        
        if requestType == CWRequestType.GET {
            GET(URLString, parameters: parameters, success: success, failure: failure)
        }else{
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
}